/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.web.utils;

import com.arisgo.cloud.common.utils.ArgsUtil;
import com.arisgo.cloud.web.model.ITree;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @author Coulson
 * @since 2023-7-2
 */
public class TreeUtil {

    /**
     * 思路
     * <ul>
     *     <li>树形结构，顶层code没有对应的node节点，如没有code为0的node，只有parentCode为0的node</li>
     *     <li>利用parentCode分组自然过滤出叶子节点</li>
     *     <li>node节点设置children，自然过滤出中间节点</li>
     *     <li>分组剩余的，全是顶层节点</li>
     * <ul/>
     */
    public static <T extends ITree<T>> List<T> convertTree(List<T> nodes) {
        if (ArgsUtil.isEmpty(nodes)) {
            return new ArrayList<>();
        }
        Map<Long, List<T>> data = Maps.newHashMap();
        nodes.forEach(node -> {
            Long key = node.getParentId();
            if (data.containsKey(key)) {
                data.get(key).add(node);
            } else {
                data.put(key, Lists.newArrayList(node));
            }
        });

        nodes.forEach(node -> {
            Long key = node.getId();
            if (data.containsKey(key)) {
                List<T> children = data.remove(key);
                children.sort(Comparator.comparing(ITree::getSort));
                node.setChildren(children);
            }
        });

        List<T> result = Lists.newArrayList();
        data.values().forEach(result::addAll);
        result.sort(Comparator.comparing(ITree::getSort));
        return result;
    }

}
